#pragma once

//命名管道的特性和匿名管道是一样的，但是有一点不同，就是命名管道可以完成不同进程间
//的通信
#include <iostream>
#include <string>
#include <sys/stat.h>
#include <sys/types.h>
#include <string.h>
#include <fcntl.h>
#include <unistd.h>

#define FIFO_FILE "fifo"
#define ERR_EXIT(m)\
do\
{\
    perror(m);\
    exit(1);\
}\
while(0)

//两个类分开的原因是，让只有server端可以创建管道，client不需要再次创建，直接进行操作即可
class NamedFifo
{
    public:
    NamedFifo(const std::string& path, const std::string& name)
        : _name(name), _path(path)
    {
        //完成创建管道文件的操作
        umask(0);//防止umask影响
        _fifoname = _path + "/" + _name;
        int n = mkfifo(_fifoname.c_str(), 0666);//文件名+权限即可
        if(n < 0)
        {
            std::cerr << "mkfifo fail" << std::endl;
        }
        else{
            ERR_EXIT("mkfifo");
        }
    }

    ~NamedFifo()
    {
        //删除管道文件，当返回值为0时，删除时成功的
        int number = unlink(_fifoname.c_str());
        if(number == 0)
        {
            std::cout << "close success" << std::endl;
        }
        else
        {
            std::cout << "close fail" << std::endl;
            ERR_EXIT("close");
        }
    }
    private:
    std::string _path;
    std::string _name;
    std::string _fifoname;
};

class FileOper
{
    public:
    FileOper(const std::string& path, const std::string& name) : _name(name), _path(path)
    {
        _fifoname = _path + "/" + _name;
    }

    void OpenForRead()
    {
        _fd = open(_fifoname.c_str(), O_RDONLY);
        if(_fd < 0)
        {
            std::cerr << "open fail" << std::endl;
        }
    }

    void OpenForWrite()
    {
        _fd = open(_fifoname.c_str(), O_WRONLY);
        if(_fd < 0)
        {
            std::cerr << "open fail" << std::endl;
        }
    }

    void Read()
    {
        
        while(1)
        {
            char buffer[1024];
        int n = read(_fd, buffer, sizeof(buffer) - 1);//留一个位置给\0
        if(n > 0)
        {
            buffer[n] = 0;
            std::cout << "client says:" << buffer << std::endl;
        }
        else if(n == 0)
        {
            std::cout << "file ends" << std::endl;
            break;
        }
        else
        {
            std::cout << "read fail" << std::endl;
            ERR_EXIT("read");
        }
    }
    }

    void Write()
    {
        pid_t id = getpid();
    int cnt = 0;
    while(1)
    {
        std::cout << "Please enter#" << std::endl;
        std::string message;
        getline(std::cin, message);//以行为单位获取字符串
        //c_str的作用是转为C语言的const char*（string内除了const char*还有一个int的size）
        message += ", message number is: " + std::to_string(cnt++) + " [" + std::to_string(id) + "]";
        write(_fd, message.c_str(), message.size());//unistd.h
    }
    }

    void Close()
    {
        if(_fd > 0)
        {
            close(_fd);
        }
    }

    ~FileOper()
    {

    }
    private:
    std::string _path;
    std::string _name;
    std::string _fifoname;
    int _fd;
};